package org.geekbang.time;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

@Slf4j
public class ExecutorServiceDemo {

    public static CountDownLatch countDownLatch = new CountDownLatch(100);

    public  static ThreadPoolExecutor threadPoolExecutor =   new ThreadPoolExecutor(
            2,
            2,
            0L,
            TimeUnit.SECONDS,
            //阻塞队列太小会导致程序被阻塞住，无法被中断，适当的得增加阻塞队列
            new LinkedBlockingDeque<>(1000));


    public static void main(String[] args) {
        List<Integer> resultList = new ArrayList<>(100);
        IntStream.range(0,100).forEach(resultList::add);

        //分段, 10批
        List<List<Integer>> split = CollUtil.split(resultList, 10);
        for (List<Integer> list : split) {
            threadPoolExecutor.execute(() -> {
                list.forEach(i -> {
                    try {
                        log.info(String.valueOf(i));
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        log.error(e.getMessage());
                    } finally {
                        countDownLatch.countDown();
                    }
                });
            });
        }

        try {
            countDownLatch.await();
            log.info("countDownLatch.await()");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
